//
//  MenuItemImageView.swift
//  CMB250716
//
//  Created by Andy Lau on 16/7/25.
//

import Foundation
import SwiftUI

// 菜品图片视图组件
struct MenuItemImageView: View {
    let imageSource: ImageSource
    let width: CGFloat?
    let height: CGFloat
    let cornerRadius: CGFloat
    let contentMode: ContentMode
    
    // 计算属性：获取远程URL
    private var remoteURL: URL? {
        guard case let .remote(urlString) = imageSource else { return nil }
        
        // 处理相对URL，添加API基础URL
        let fullURLString: String
        if urlString.hasPrefix("http") {
            fullURLString = urlString
        } else {
            // 使用API基础URL
            let apiBaseURL = AppConfig.apiBaseURL
            if urlString.hasPrefix("/") {
                // 直接使用完整路径
                fullURLString = apiBaseURL + urlString
            } else if urlString.contains("uploads/menu-images/") {
                // 已经包含正确的路径格式，直接添加基础URL
                fullURLString = apiBaseURL + "/" + urlString
            } else {
                // 默认添加到uploads/menu-images目录
                fullURLString = apiBaseURL + "/uploads/menu-images/" + urlString
            }
        }
        
        // 清理URL中的多余斜杠和空格
        var cleanedURLString = fullURLString
        
        // 修复多重斜杠问题 - 先处理http://后的多余斜杠
        if let range = cleanedURLString.range(of: "://") {
            let protocolPart = cleanedURLString[..<range.upperBound]
            var path = String(cleanedURLString[range.upperBound...])
            
            // 处理路径中的多余斜杠
            while path.contains("//") {
                path = path.replacingOccurrences(of: "//", with: "/")
            }
            
            cleanedURLString = String(protocolPart) + path
        } else {
            // 没有协议前缀的情况，直接处理多余斜杠
            while cleanedURLString.contains("//") {
                cleanedURLString = cleanedURLString.replacingOccurrences(of: "//", with: "/")
            }
        }
        
        // 处理特殊字符和空格
        cleanedURLString = cleanedURLString.trimmingCharacters(in: .whitespacesAndNewlines)
        
        // 特殊处理棒棒类食品图片URL
        if cleanedURLString.contains("棒") || cleanedURLString.contains("stick") {
            print("DEBUG: 检测到棒棒类食品图片URL: \(cleanedURLString)")
        }
        
        // 使用更严格的URL编码
        let allowedCharSet = CharacterSet.urlQueryAllowed.subtracting(CharacterSet(charactersIn: "#%^{}[]|\\<>\" "))
        cleanedURLString = cleanedURLString.addingPercentEncoding(withAllowedCharacters: allowedCharSet) ?? cleanedURLString
        
        print("DEBUG: 构建的图片URL: \(cleanedURLString)")
        return URL(string: cleanedURLString)
    }
    
    // 本地图片已移除，不再支持本地图片资源
    private var localImage: UIImage? {
        return nil
    }
    
    // 计算属性：获取占位符系统图片名称
    private var placeholderSystemName: String {
        if case let .placeholder(systemName) = imageSource {
            return systemName
        }
        return "photo"
    }
    
    init(imageSource: ImageSource, width: CGFloat? = nil, height: CGFloat = 120, cornerRadius: CGFloat = 16, contentMode: ContentMode = .fill) {
        self.imageSource = imageSource
        self.width = width
        self.height = height
        self.cornerRadius = cornerRadius
        self.contentMode = contentMode
    }
    
    var body: some View {
        let frameWidth = width ?? height
        
        ZStack {
            // 远程图片
            if let url = remoteURL {
                AsyncImage(url: url) { image in
                    image.resizable()
                         .aspectRatio(contentMode: contentMode)
                } placeholder: {
                    ZStack {
                        Color.gray.opacity(0.3)
                        ProgressView()
                    }
                }
            }
            // 占位符
            else {
                // 渐变背景
                LinearGradient(
                    colors: [
                        Color.gray.opacity(0.6),
                        Color.gray.opacity(0.4)
                    ],
                    startPoint: .topLeading,
                    endPoint: .bottomTrailing
                )
                
                VStack {
                    Image(systemName: placeholderSystemName)
                        .font(.system(size: 32, weight: .light))
                        .foregroundColor(.white.opacity(0.8))
                    
                    Text("📷")
                        .font(.system(size: 24))
                }
            }
        }
        .frame(width: frameWidth, height: height)
        .cornerRadius(cornerRadius)
    }
}
 
 // 预览
struct MenuItemImageView_Previews: PreviewProvider {
    static var previews: some View {
        VStack(spacing: 20) {
            // 占位符示例（本地图片已移除）
            MenuItemImageView(
                imageSource: ImageSource.placeholder("photo"),
                height: 120
            )
            
            // 网络图片示例
            MenuItemImageView(
                imageSource: ImageSource.remote("https://example.com/image.jpg"),
                height: 120
            )
            
            // 占位符示例
            MenuItemImageView(
                imageSource: ImageSource.placeholder("fork.knife"),
                height: 120
            )
        }
        .padding()
        .background(Color.black)
    }
}